package com.powernode.reggie.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @description: MB 自动填中字段实现
 * @author: www
 * @time: 2023/3/8 14:29
 */
@Component  //Spring 管理
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入操作自动填充，save中填充代码可以注释掉
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("自动填充 insert...");

        log.info(metaObject.toString());
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("createUser", BaseContext.getCurrentId());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());


        // 如果实体类中有下单时间，才会自动填充  自动填充的下单时间字段和支付时间字段
        if (metaObject.hasSetter("orderTime")) {
            metaObject.setValue("orderTime", LocalDateTime.now());
        }
        if (metaObject.hasSetter("checkoutTime")) {
            metaObject.setValue("checkoutTime", LocalDateTime.now());
        }

    }

    /**
     * 更新操作时自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("自动填充 update...");
//        long id = Thread.currentThread().getId();
//        log.info("线程id：{}",id);
        log.info(metaObject.toString());

        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());//放入获取到的当前线程登录用户id
    }
}
